<?php
namespace app\service;

use support\Log;

class WechatService
{
    private $config;

    public function __construct()
    {
        $this->config = config('wechat');
    }

    public function sendAlarmNotification($openId, $deviceId, $deviceName, $alarmMsg)
    {


        // dd($deviceName, $alarmMsg);

        try {
            // 获取访问令牌
            $accessToken = $this->getAccessToken();

            // 准备订阅消息数据
            $data = [
                'touser' => $openId,
                'template_id' => $this->config['alarm_template_id'],
                'page' => 'pages/device/detail?id=' . $deviceId,
                'data' => [
                    'thing7' => ['value' => $deviceName],
                    'thing8' => ['value' => $alarmMsg],
                    // 'time4' => ['value' => date('Y-m-d H:i:s')]
                ]
            ];

            Log::info('wx_request', ['data' => $data]);

            // 发送订阅消息
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$accessToken}";
            $response = $this->httpPost($url, json_encode($data));

            // var_dump($response);

            Log::info('wx_response', ['response' => $response]);

            return true;
        } catch (\Exception $e) {
            error_log("WeChat notification sending failed: " . $e->getMessage());
            return false;
        }
    }

    private function getAccessToken()
    {
        $cacheFile = runtime_path() . '/wechat_access_token.cache';
        $expires = 7000; // 微信官方有效期7200秒，预留200秒
        // 1. 先查缓存
        if (is_file($cacheFile)) {
            $cache = json_decode(file_get_contents($cacheFile), true);
            if ($cache && isset($cache['access_token']) && isset($cache['expire_time']) && $cache['expire_time'] > time()) {
                return $cache['access_token'];
            }
        }
        // 2. 请求微信接口
        $appid = $this->config['appid'];
        $secret = $this->config['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $resp = file_get_contents($url);
        $data = json_decode($resp, true);
        if (isset($data['access_token'])) {
            $cache = [
                'access_token' => $data['access_token'],
                'expire_time' => time() + $expires
            ];
            file_put_contents($cacheFile, json_encode($cache));
            return $data['access_token'];
        } else {
            throw new \Exception('获取微信access_token失败: ' . ($data['errmsg'] ?? '未知错误'));
        }
    }

    private function httpPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
} 